package com.xmqian.app.project.common.helper;

import com.coszero.common.config.AppControl;
import com.coszero.common.network.ApiFactory;
import com.coszero.utils.utils.LogX;
import com.xmqian.app.project.common.network.ApiService;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by xuyougen on 2018/4/11.
 */

public class RetrofitHelper {
    String TAG = this.getClass().getSimpleName();
    private static final int CONNECT_TIMEOUT = 8;
    private static final int READ_TIMEOUT = 8;
    private static final int WRITE_TIMEOUT = 8;

    private Retrofit mRetrofit;
    private static RetrofitHelper INSTANCE;
    /**
     * 网络日志打印拦截器
     * 包含header、body数据
     * interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
     * setlevel用来设置日志打印的级别，共包括了四个级别：NONE,BASIC,HEADER,BODY
     * BASEIC:请求/响应行
     * HEADER:请求/响应行 + 头
     * BODY:请求/响应行 + 头 + 体
     */
    private HttpLoggingInterceptor interceptor =
            new HttpLoggingInterceptor(message -> {
                try {
                    LogX.i(TAG, message);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogX.e(TAG, message);
                }
            });

    private RetrofitHelper() {
        init();
    }

    private void init() {
        OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder();
        if (AppControl.IS_DEBUG_VERSION) {
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            clientBuilder.addInterceptor(interceptor);
//                .addInterceptor(new HttpInterceptorUtils())
        }
        clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).build();
        OkHttpClient client = clientBuilder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiFactory.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
    }

    public static RetrofitHelper getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new RetrofitHelper();
        }
        return INSTANCE;
    }

    public ApiService getService() {
        return mRetrofit.create(ApiService.class);
    }

}
